<template>
  <div class="bigbox">
    <!-- 表头盒子 -->
    <!-- 盒子主体 -->
    <div class="mainbox">
      <div class="title">
        <div class="code">表编码: {{ tableInfo.tableCode }}</div>
        <div class="name">表名称: {{ tableInfo.tableName }}</div>
        <div class="edit" @click="tableEdit"><i class="el-icon-edit"></i></div>
      </div>
      <div class="top">
        <div class="left">
          <div class="search">
            <el-input
              placeholder="请输入关键字搜索"
              prefix-icon="el-icon-search"
              v-model="inputValue"
            >
            </el-input>
          </div>
        </div>
        <div class="towBtn">
          <button @click="chongzhi" class="button">重置</button>
          <button @click="chaxun" class="button chaxun">查询</button>
        </div>
      </div>
      <div class="bodybox">
        <!-- 新增按钮 -->
        <!-- 循环图片盒子 -->
        <div class="table">
          <div class="titlebox">
            <div class="text"></div>
            <div
              class="right"
              :style="{ alignItems: 'center', lineHeight: '32.5px' }"
            >
              <button
                type="primary"
                size="small"
                class="bewdao daochu"
                @click="jbyj1"
              >
                建表语句
              </button>
              <button
                type="primary"
                size="small"
                class="bewdao daochu"
                @click="indexOpen"
              >
                索引管理
              </button>
              <button
                type="primary"
                size="small"
                class="bewdao daochu"
                @click="dialogOpen"
              >
                同步字段
              </button>
              <el-tooltip
                class="item"
                effect="dark"
                content="刷新"
                placement="top"
              >
                <span
                  @click="shuaxin"
                  :style="{ cursor: 'pointer', fontSize: '20px' }"
                  ><i class="el-icon-refresh-right"></i
                ></span>
              </el-tooltip>
              <el-dropdown trigger="click" @command="command">
                <span class="el-dropdown-link">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="密度"
                    placement="top"
                  >
                    <span :style="{ cursor: 'pointer', fontSize: '20px' }"
                      ><i class="el-icon-d-caret"></i
                    ></span>
                  </el-tooltip>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item class="dropdown-list" command="默认"
                    >默认</el-dropdown-item
                  >
                  <el-dropdown-item class="dropdown-list" command="中等"
                    >中等</el-dropdown-item
                  >
                  <el-dropdown-item class="dropdown-list" command="紧凑"
                    >紧凑</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="tableList"
            style="width: 99%"
            border
            height="400px"
            id="exportTabyong"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center',
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column align="left" prop="fieldCode" label="字段编码">
            </el-table-column>
            <el-table-column align="left" prop="fieldName" label="字段名称">
            </el-table-column>
            <el-table-column align="left" prop="fieldType" label="字段类型">
              <template slot-scope="scope">
                {{
                  propTypeList.find((i) => i.value === scope.row.fieldType)
                    ?.text
                }}
              </template>
            </el-table-column>
            <el-table-column align="left" prop="nullEnable" label="是否可空">
              <template slot-scope="scope">
                <span>{{ scope.row.nullEnable ? "是" : "否" }}</span>
              </template>
            </el-table-column>
            <el-table-column align="left" prop="fieldLength" label="长度">
            </el-table-column>
            <el-table-column align="left" prop="fieldAccuracy" label="精度">
            </el-table-column>
            <el-table-column
              align="left"
              width="250px"
              prop="fieldExplain"
              label="字段描述"
            >
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <div class="table-cz">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="编辑"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-edit"
                      @click="edit(scope.row)"
                    ></i
                  ></el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除"
                    placement="top"
                  >
                    <i
                      style="font-size: 14px; color: red; cursor: pointer"
                      class="el-icon-delete"
                      @click="del(scope.row)"
                    ></i
                  ></el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="上移"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-upload2"
                      @click="move('up', scope.row)"
                    ></i
                  ></el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="下移"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-download"
                      @click="move('down', scope.row)"
                    ></i
                  ></el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 同步字段弹框 -->
        <el-dialog
          :show-close="true"
          :visible.sync="tableVisible"
          width="1000px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <TableUse
            v-loading="loading2"
            :data="syncList"
            border
            ref="table"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center',
            }"
            :name="'propertyId'"
            :tableConfig="tableConfig"
            @selection-change="chooseList"
          >
            <template v-slot:propertyType="row">
              {{
                propTypeList.find((i) => i.value === row.row.propertyType)?.text
              }}
            </template>
            <!--  <template v-slot:extendProperty="row">
              <span>{{ row.row.extendProperty ? "是" : "否" }}</span>
            </template> -->
          </TableUse>
          <div style="margin-top: 20px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="diaClose">取 消</el-button>
              <el-button type="primary" @click="tableSubmit">确 定</el-button>
            </span>
          </div>
        </el-dialog>
        <!-- 储存表名称修改 -->
        <el-dialog
          :show-close="true"
          :visible.sync="editVisible"
          width="500px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <el-form
            ref="tableForm"
            :rules="tableRules"
            :model="editForm"
            label-width="110px"
          >
            <el-form-item label="表名称" prop="tableName">
              <el-input v-model="editForm.tableName"></el-input>
            </el-form-item>
            <el-form-item label="表说明" prop="tableExplain">
              <el-input
                v-model="editForm.tableExplain"
                type="textarea"
                :rows="4"
                resize="none"
              ></el-input>
            </el-form-item>
          </el-form>
          <!-- 弹窗内容 -->
          <div style="margin-top: 10px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="diaClose">取 消</el-button>
              <el-button type="primary" @click="editSubmit">保 存</el-button>
            </span>
          </div>
        </el-dialog>
        <!-- 字段编辑 -->
        <el-dialog
          :show-close="true"
          :visible.sync="dialogVisible"
          v-if="dialogVisible"
          width="500px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <div class="dialog">
            <!-- 企业下拉 -->
            <el-form
              ref="dialogForm"
              :rules="rules"
              :model="dialogForm"
              label-width="110px"
            >
              <el-form-item label="字段名" prop="fieldName">
                <el-input v-model="dialogForm.fieldName"></el-input>
              </el-form-item>
              <el-form-item label="字段长度" prop="fieldLength">
                <el-input v-model="dialogForm.fieldLength"></el-input>
              </el-form-item>
              <el-form-item label="字段精度" prop="fieldAccuracy">
                <el-input v-model="dialogForm.fieldAccuracy"></el-input>
              </el-form-item>
              <el-form-item label="是否可空" prop="nullEnable">
                <el-switch
                  v-model="dialogForm.nullEnable"
                  active-color="#13ce66"
                  inactive-color="#efefef"
                >
                </el-switch>
              </el-form-item>
              <el-form-item label="默认值" prop="defaultValue">
                <el-input v-model="dialogForm.defaultValue"></el-input>
              </el-form-item>
              <el-form-item label="字段说明" prop="fieldExplain">
                <el-input
                  v-model="dialogForm.fieldExplain"
                  type="textarea"
                  :rows="4"
                  resize="none"
                ></el-input>
              </el-form-item>
            </el-form>
            <!-- 弹窗内容 -->
          </div>
          <div style="margin-top: 10px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="diaClose">取 消</el-button>
              <el-button type="primary" @click="add">保 存</el-button>
            </span>
          </div>
        </el-dialog>
        <!-- 建表语句 -->
        <el-dialog
          :show-close="true"
          :visible.sync="sqlVisible"
          v-if="sqlVisible"
          width="800px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <el-input
            type="textarea"
            rows="15"
            v-model="textarea"
            readonly
            resize="none"
          ></el-input>
          <div style="margin-top: 10px">
            <span slot="footer" class="dialog-footer">
              <div>
                <el-button type="primary" @click="jbyj2">建表语句</el-button>
              </div>
              <div>
                <el-button type="primary" @click="actions">执 行</el-button>
                <el-button @click="diaClose">关 闭</el-button>
              </div>
            </span>
          </div>
        </el-dialog>
        <el-dialog
          :visible.sync="jbyjVisible"
          width="30%"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          append-to-body
          :show-close="false"
        >
          <div :style="{ 'max-height': '400px', 'overflow-y': 'auto' }">
            <span v-html="text.replace(/\n/g, '<br>')"></span>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="jbyjVisible = false"
              >确 定</el-button
            >
          </span>
        </el-dialog>

        <!-- 索引弹窗 -->
        <el-dialog
          :show-close="true"
          :visible.sync="indexVisible"
          v-if="indexVisible"
          width="1000px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <IndexMaintain :data="storageData"></IndexMaintain>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  delFieldApi,
  downFieldApi,
  editFieldApi,
  editTableApi,
  executeSqlApi,
  getCreateSqlApi,
  getExecuteSqlApi,
  getFieldDataApi,
  getPropTypeListApi,
  getSyncListApi,
  getTableDataApi,
  getTableListApi,
  syncTableApi,
  upFieldApi
} from '@/api/Device-all/Device-model'
import TableUse from '../../components/TableUse.vue'
import IndexMaintain from './IndexMaintain.vue'
export default {
  name: 'DeviceTableMaintain',
  components: { TableUse, IndexMaintain },
  props: {
    storageData: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      filterText: '',
      inputValue: '',
      tableData: [],
      loading: false,
      loading2: false,
      iissize: 'medium',
      tableRules: {
        tableName: [
          { required: true, message: '请输入表名称', trigger: 'blur' }
        ]
      },
      dialogForm: {},
      editForm: {},
      tableInfo: {},
      form: {},
      propTypeList: [],
      rules: {
        fieldName: [
          { required: true, message: '请输入字段名', trigger: 'blur' }
        ],
        fieldLength: [
          { required: true, message: '请输入字段长度', trigger: 'blur' }
        ],
        fieldAccuracy: [
          { required: true, message: '请输入字段精度', trigger: 'blur' }
        ],
        nullEnable: [
          { required: true, message: '请选择是否可空', trigger: 'change' }
        ]
      },
      deflist: [],
      syncList: [],
      tableList: [],
      textarea: '',
      text: '',
      dialogVisible: false,
      tableVisible: false,
      indexVisible: false,
      editVisible: false,
      jbyjVisible: false,
      sqlVisible: false,
      tableConfig: [
        {
          align: 'left',
          prop: 'propertyCode',
          label: '属性编码'
        },
        {
          align: 'left',
          prop: 'propertyName',
          label: '属性名称'
        },
        {
          align: 'left',
          prop: 'propertyType',
          label: '属性类型'
        },
        {
          align: 'left',
          prop: 'propertyClassName',
          label: '所属类名称'
        }
      ]
      // pageobj: {
      //   _pageNo: 0,
      //   _pageSize: 15,
      // },
      // total: 0,
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  created () {
    this.getTableData()
    this.getPropTypeList()
  },
  mounted () {
    this.getTableList()
  },
  methods: {
    async jbyj1 () {
      const res = await getExecuteSqlApi(this.storageData.tableId)
      console.log(res)
      this.textarea = res.data.content
      this.sqlVisible = true
    },
    async jbyj2 () {
      const res = await getCreateSqlApi(this.storageData.tableId)
      console.log(res)
      this.text = res.data.content
      this.jbyjVisible = true
    },
    // 执行
    async actions () {
      const res = await executeSqlApi({ tableId: this.storageData.tableId })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: res.message,
          duration: 2000
        })
        this.sqlVisible = false
      }
    },
    // 查询表模型基本信息
    async getTableData () {
      const res = await getTableDataApi(this.storageData.tableId)
      this.tableInfo = res.data.entity
    },
    // 查询表字段列表
    async getTableList () {
      this.loading = true
      const res = await getTableListApi(this.storageData.tableId)
      this.deflist = res.data.list
      this.tableList = res.data.list
      this.loading = false
    },
    // 待同步表字段列表
    async getSyncList () {
      this.loading2 = true
      const res = await getSyncListApi(this.storageData.tableId)
      this.syncList = res.data.list
      this.loading2 = false
    },
    // 获取属性类型
    async getPropTypeList () {
      const res = await getPropTypeListApi()
      this.propTypeList = res.data.list
    },

    // 同步字段弹窗打开
    async dialogOpen () {
      this.$set(this.form, 'tableId', this.storageData.tableId)
      this.getSyncList()
      this.tableVisible = true
    },
    // 索引弹窗打开
    indexOpen () {
      this.indexVisible = true
    },

    // 弹窗关闭
    diaClose () {
      this.dialogVisible = false
      this.tableVisible = false
      this.editVisible = false
      this.indexVisible = false
      this.sqlVisible = false
      this.dialogForm = {}
      this.form = {}
    },
    async shuaxin () {
      await this.chaxun()
      this.$message({
        message: '列表刷新成功',
        type: 'success',
        duration: 2000
      })
    },
    // 查询分页信息
    async chaxun () {
      await this.getTableList()
      const list = [...this.deflist]
      if (this.inputValue) {
        this.tableList = list.filter(
          (item) =>
            item.fieldCode.includes(this.inputValue) ||
            item.fieldName.includes(this.inputValue)
        )
      } else {
        this.tableList = [...list]
      }
    },
    command (val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    // 表字段修改提交
    async add () {
      await this.$refs.dialogForm.validate()
      console.log(this.dialogForm)
      const res = await editFieldApi(this.dialogForm)
      if (res.code == 200) {
        this.$message({
          message: res.message,
          type: 'success',
          duration: 2000
        })
        this.getTableList()
        this.diaClose()
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 2000
        })
      }
    },
    // 移动
    async move (type, item) {
      this.$confirm('此操作将移动表字段, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res =
            type === 'up'
              ? await upFieldApi({
                fieldId: item.fieldId
              })
              : await downFieldApi({
                fieldId: item.fieldId
              })
          console.log(res)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: res.message,
              duration: 2000
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message,
              duration: 2000
            })
          }
          this.getTableList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消移动',
            duration: 2000
          })
        })
    },
    // 储存表修改
    async tableEdit () {
      const data = { ...this.tableInfo }
      this.editForm = {
        tableId: data.tableId,
        tableName: data.tableName,
        tableExplain: data.tableExplain
      }
      this.editVisible = true
    },
    // 编辑
    async edit (item) {
      console.log(item)
      const res = await getFieldDataApi(item.fieldId)
      // console.log(res)
      const data = res.data.entity
      this.dialogForm = {
        fieldName: data.fieldName,
        fieldLength: data.fieldLength,
        fieldAccuracy: data.fieldAccuracy,
        nullEnable: data.nullEnable,
        defaultValue: data.defaultValue,
        fieldExplain: data.fieldExplain,
        fieldCode: data.fieldCode,
        fieldId: data.fieldId,
        fieldType: data.fieldType
      }
      this.$forceUpdate()
      this.dialogVisible = true
    },
    // 删除
    async del (item) {
      this.$confirm('此操作将永久删除该表字段, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await delFieldApi(item.fieldId)
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.message,
                duration: 2000
              })
              this.getTableList()
            } else {
              this.$message({
                type: 'error',
                message: res.message,
                duration: 2000
              })
            }
          } catch (e) {
            console.log(e)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    chongzhi () {
      this.inputValue = ''
      this.getTableList()
    },
    chooseList (arr) {
      console.log(arr)
      this.form.propertyId = arr
    },
    // 同步表字段 保存
    async tableSubmit () {
      console.log(this.form)
      const res = await syncTableApi(this.form)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: res.message,
          duration: 2000
        })
        this.getTableList()
        this.getSyncList()
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 2000
        })
      }
      console.log(res)
    },
    // 修改储存表保存
    async editSubmit () {
      console.log(this.form)
      const res = await editTableApi(this.editForm)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: res.message,
          duration: 2000
        })
        this.getTableData()
        this.getSyncList()
        this.diaClose()
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 2000
        })
      }
      console.log(res)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep textarea {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
.table-cz {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  line-height: 40px;
  border: 1px solid #d9d9d9;
  text-align: center;
}
.avatar {
  width: 40px;
  height: 40px;
  display: block;
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
}
.bigbox {
  background-color: #f1f1f1;
  min-height: 100%;
  padding: 9px;
  display: flex;
  .mainbox {
    position: relative;
    flex: 1;
    .title {
      position: absolute;
      display: flex;
      font-size: 20px;
      top: -48px;
      left: 0;
      .code {
        width: 400px;
        margin-right: 50px;
      }
      .name {
        margin-right: 50px;
      }
      .edit {
        color: #4095e5;
        cursor: pointer;
      }
    }
    .top {
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 80px;
      background-color: #fff;
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 20px;
      align-items: center;
      .left {
        display: flex;
        align-items: center;
        .group-select {
          width: 200px;
          margin-right: 10px;
        }
        .group-add {
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          border: 1px solid #dcdfe6;
          border-radius: 5px;
          width: 25px;
          height: 25px;
          margin-right: 20px;
        }
        .search {
          display: flex;
          align-items: center;
          width: 200px;
        }
      }
    }
    .bodybox {
      position: relative;
      background-color: #fff;
      padding: 20px;
      padding-bottom: 30px;
      .pagination {
        position: absolute;
        right: 20px;
        bottom: 10px;
      }
      .table {
        .titlebox {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          .text {
            font-size: 16px;
          }
          .right {
            align-items: center;
            i {
              margin-left: 10px;
            }
            .bewdao {
              width: 70px;
              height: 32px;
              margin-right: 20px;
            }
            .daochu {
              background-color: #1890ff;
              color: #fff;
              border: none;
              border-radius: 3px;
            }
          }
        }
      }
      .dialog {
        .title {
          font-size: 28px;
          margin-bottom: 30px;
        }
        .text {
          font-size: 12px;
          color: #3b8eea;
        }
      }
    }
  }
}

::v-deep .el-select {
  width: 100%;
}
::v-deep .el-input {
  height: 32px;
}
::v-deep .el-input__inner {
  height: 32px;
}
::v-deep .el-input__icon {
  line-height: 1;
}
.el-select-dropdown__item {
  padding-left: 10px;
}
::v-deep .el-date-editor {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}
.button {
  width: 63px;
  height: 32px;
  margin-right: 5px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
}
.chaxun {
  background-color: #1890ff;
  color: #fff;
}
::v-deep .el-range-separator {
  line-height: 25px;
}
.timeTitle {
  height: 50px;
}

.dropdown-list {
  padding: 0;
  text-align: center;
  width: 50px;
}

.change-type {
  width: 100px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 1);
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.node-img {
  width: 16px;
  height: 16px;
  margin-right: 5px;
  vertical-align: bottom;
}
</style>
